export default class SrsPlayer {

    private pc = new RTCPeerConnection()
    public stream = new MediaStream()

    public getConf(url) {

        return {
            apiUrl: '/rtc/v1/play/',
            // @ts-ignore
            tid: Number(parseInt(new Date().getTime() * Math.random() * 100)).toString(16).substr(0, 7),
            streamUrl: url
        }
    }

    public async play(url) {
        this.init()
        //this.pc.addTransceiver("audio", {direction: "recvonly"})
        this.pc.addTransceiver("video", {direction: "recvonly"})
        const offer = await this.pc.createOffer()
        await this.pc.setLocalDescription(offer)

        const conf = this.getConf(url) 
        const data = {
            api: conf.apiUrl,
            tid: conf.tid,
            streamurl: conf.streamUrl,
            clientip: null,
            sdp: offer.sdp
        }
        const session = await ((await fetch(conf.apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data),
        })).json() )

        //console.log("offer.sdp:");
        //console.log(offer.sdp);
        //console.log("session.sdp:");
        //console.log(session.sdp);
        let answerSdp = this.convertAnswerSdp(offer.sdp, session.sdp);
        //console.log("answerSdp:");
        //console.log(answerSdp);
        await this.pc.setRemoteDescription(
            new RTCSessionDescription({type: 'answer', sdp: answerSdp})
        )

    }

    public convertAnswerSdp(offerSdp, answerSdp) {
        let indexOfOfferVideo = offerSdp.indexOf("m=video")
        let indexOfOfferAudio = offerSdp.indexOf("m=audio")
        if (indexOfOfferVideo == -1 || indexOfOfferAudio == -1) {
            return answerSdp
        }
        let indexOfAnswerVideo = answerSdp.indexOf("m=video")
        let indexOfAnswerAudio = answerSdp.indexOf("m=audio")
        if (indexOfAnswerVideo == -1 || indexOfAnswerAudio == -1) {
            return answerSdp
        }

        let isFirstOfferVideo = indexOfOfferVideo < indexOfOfferAudio
        let isFirstAnswerVideo = indexOfAnswerVideo < indexOfAnswerAudio
        if (isFirstOfferVideo == isFirstAnswerVideo) {
            return answerSdp
        } 

        if (isFirstAnswerVideo) {
            return answerSdp.substring(0, indexOfAnswerVideo) 
              + answerSdp.substring(indexOfAnswerAudio, answerSdp.length)
              + answerSdp.substring(indexOfAnswerVideo, indexOfAnswerAudio)
        }
        else {
            return answerSdp.substring(0, indexOfAnswerAudio) 
                + answerSdp.substring(indexOfAnswerVideo, answerSdp.length)
                + answerSdp.substring(indexOfAnswerAudio, indexOfAnswerVideo)
        }
    }

    public close() {
        if (this.pc) {
            this.pc.close()
            // @ts-ignore
            this.pc = null
        }
        if (this.stream) {
            // @ts-ignore
            this.stream = null
        }
    }

    public addEvent() {
        this.pc.ontrack = (event) => {
            this.stream.addTrack(event.track)
        }
        this.pc.onconnectionstatechange = (event) => {
            console.log(event)
        }
        this.pc.oniceconnectionstatechange = (event) => {
            console.log(event)
        }
        this.pc.onicecandidateerror = (event) => {
            console.log(event)
        }
    }

    public init() {
        if (this.pc == null) {
            this.pc = new RTCPeerConnection()
        }
        if (this.stream == null) {
            this.stream = new MediaStream()
        }
        this.addEvent()
    }

}